package com.gzhryc.shared_device.bxscn.api;

import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.bxscn.api.protocol.*;
import com.gzhryc.shared_device.bxscn.core.IBXSCNNetworkService;
import com.gzhryc.shared_device.bxscn.core.models.BXSCNExecuteResult;
import com.gzhryc.shared_device.bxscn.core.models.BXSCNLeaseCommand;
import com.gzhryc.shared_device.bxscn.core.models.BXSCNOpenSlotCommand;
import com.gzhryc.shared_device.iot.core.IOTNodeEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

public class BXSCNHttpAPINetworkService implements IBXSCNNetworkService {

    private static Logger log = Logger.getLogger(BXSCNHttpAPINetworkService.class);

    private IOTNodeEntity iotNode;
    private CloseableHttpClient httpClient;

    public BXSCNHttpAPINetworkService(IOTNodeEntity iotNode) {
        this.iotNode = iotNode;
        this.httpClient = HttpClients.createDefault();
    }

    @Override
    public BXSCNExecuteResult lease(BXSCNLeaseCommand leaseCommand) {
        BXSCNExecuteResult result = new BXSCNExecuteResult(BXSCNExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/bxscn/lease.do").build();

            BXSCNHttpLeaseRequest apiReq = new BXSCNHttpLeaseRequest();
            apiReq.getBody().setDeviceSn(leaseCommand.getDeviceSn());
            apiReq.getBody().setSlotNum(leaseCommand.getSlotNum());
            apiReq.getBody().setTradeNo(leaseCommand.getTradeNo());
            apiReq.getBody().setMessageId(leaseCommand.getMessageId());

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("便携式储能租借返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    BXSCNHttpLeaseResponse apiResp = JsonTools.fromJson(str, BXSCNHttpLeaseResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("便携式储能租借错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public BXSCNExecuteResult openSlot(BXSCNOpenSlotCommand openSlotCommand) {
        BXSCNExecuteResult result = new BXSCNExecuteResult(BXSCNExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/bxscn/open_slot.do").build();

            BXSCNHttpReturnRequest apiReq = new BXSCNHttpReturnRequest();
            apiReq.getBody().setDeviceSn(openSlotCommand.getDeviceSn());
            apiReq.getBody().setSlotNum(openSlotCommand.getSlotNum());
            apiReq.getBody().setMessageId(openSlotCommand.getMessageId());

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("便携式储能开仓返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    BXSCNHttpReturnResponse apiResp = JsonTools.fromJson(str, BXSCNHttpReturnResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("便携式储能开仓错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public BXSCNExecuteResult forceEjectDevice(String deviceSn, Integer slotNum) {
        BXSCNExecuteResult result = new BXSCNExecuteResult(BXSCNExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/bxscn/eject.do").build();

            BXSCNHttpEjectRequest apiReq = new BXSCNHttpEjectRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setSlotNum(slotNum);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("便携式储能租借强制弹出返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    BXSCNHttpEjectResponse apiResp = JsonTools.fromJson(str, BXSCNHttpEjectResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("便携式储能租借强制弹出错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public BXSCNExecuteResult forceEjectDevice(String deviceSn) {
        BXSCNExecuteResult result = new BXSCNExecuteResult(BXSCNExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/bxscn/eject.do").build();

            BXSCNHttpEjectRequest apiReq = new BXSCNHttpEjectRequest();
            apiReq.getBody().setDeviceSn(deviceSn);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("便携式储能租借强制弹出返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    BXSCNHttpEjectResponse apiResp = JsonTools.fromJson(str, BXSCNHttpEjectResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("便携式储能租借强制弹出错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public BXSCNExecuteResult searchDevice(String deviceSn) {
        BXSCNExecuteResult result = new BXSCNExecuteResult(BXSCNExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/bxscn/search.do").build();

            BXSCNHttpSearchRequest apiReq = new BXSCNHttpSearchRequest();
            apiReq.getBody().setDeviceSn(deviceSn);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("便携式储能租借查询返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    BXSCNHttpSearchResponse apiResp = JsonTools.fromJson(str, BXSCNHttpSearchResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("便携式储能租借查询错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public BXSCNExecuteResult sendCmd(String deviceSn, String content) {
        BXSCNExecuteResult result = new BXSCNExecuteResult(BXSCNExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/bxscn/send_cmd.do").build();

            BXSCNHttpSendCmdRequest apiReq = new BXSCNHttpSendCmdRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setContent(content);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("便携式储能租借发送任意报文返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    BXSCNHttpSendCmdResponse apiResp = JsonTools.fromJson(str, BXSCNHttpSendCmdResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("便携式储能租借发送任意报文错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
